import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'
import Main from '@/views/main/Main.vue'
import UserList from '@/views/user/UserList.vue'
import UserSong from '@/views/user/UserSongs.vue'
import Singer from '@/views/singer/Singer.vue'
import Type from '@/views/song/Type.vue'
import SpecialList from '@/views/song/SpecialList.vue'
import Song from '@/views/song/Song.vue'
import AddSong from '@/views/song/AddSong.vue'
import Diagram from '@/views/statistics/Diagram.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    children: [
      { path: '/main', component: Main },
      { path: '/userlist', component: UserList },
      { path: '/usersong', component: UserSong },
      { path: '/singerlist', component: Singer },
      { path: '/typelist', component: Type },
      { path: '/speciallist', component: SpecialList },
      { path: '/songlist', component: Song },
      { path: '/addsong', component: AddSong },
      { path: '/diagram', component: Diagram }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 从那个路径跳转而来
  // to 是一个函数，表示放行  next() 放行  next('强制跳转的路径')
  if (to.path === '/login') {
    const tokenStr = window.sessionStorage.getItem('loginToken')
    const manger = window.sessionStorage.getItem('manger')
    if (manger !== null && tokenStr !== null) {
      return next('/home')
    } else {
      return next()
    }
  } else {
    const tokenStr = window.sessionStorage.getItem('loginToken')
    if (tokenStr === null) {
      return next('/login')
    }
  }
  next()
})

export default router
